package com.igoal.campaign.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.igoal.campaign.dao.CampaignDAO;
import com.igoal.campaign.dto.CampaignDTO;
import com.igoal.campaign.entity.Campaign;
import com.igoal.entity.DataStatus;

public class CampaignServiceImpl implements CampaignService {
	@Autowired
	CampaignDAO campaignDAO;
	
	public CampaignDTO getCampaign(Long id) {
		Campaign campaign = campaignDAO.get(id);
		
		CampaignDTO dto = new CampaignDTO();
		dto.initFrom(campaign);
		
		return dto;
	}

	public List<CampaignDTO> listCampaigns() {
		List<Campaign> entities = campaignDAO.getAllDistinct();
		List<CampaignDTO> dtos = new ArrayList<CampaignDTO>();
		
		for(Campaign campaign : entities){
			CampaignDTO dto = new CampaignDTO();
			dto.initFrom(campaign);
			dtos.add(dto);
		}
		
		return dtos;
	}

	public CampaignDTO saveCampaign(CampaignDTO campaignDTO) {
		Campaign campaign = new Campaign();
		
		campaignDTO.copyAttributesTo(campaign);
		campaign.setCreateDate(new Date());
		campaign.setUpdateDate(new Date());
		campaign.setStatus(DataStatus.USING);
		
		campaign = campaignDAO.save(campaign);
		campaignDTO.initFrom(campaign);
		
		return campaignDTO;
	}

	public CampaignDTO getCampaignByName(String name) {
		Campaign campaign = campaignDAO.getCampaignByName(name);
		if(campaign != null){
			CampaignDTO dto = new CampaignDTO();
			dto.initFrom(campaign);
			return dto;
		}
		return null;
	}
	
	public boolean isValidCampaign(CampaignDTO dto){
		Date today = new Date();
		return today.compareTo(dto.getFrom()) >= 0 && today.compareTo(dto.getTo()) <= 0;
	}

}
